package com.vr.cloudpicture.manager;

import cn.hutool.core.io.FileUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.*;
import com.qcloud.cos.model.ciModel.persistence.PicOperations;
import com.vr.cloudpicture.config.CosClientConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * COS相关通用代码，与业务无关
 *
 * @author hzh
 * @date 2025/05/07
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class CosManager {
    private final CosClientConfig cosClientConfig;
    private final COSClient cosClient;

    /**
     * 上传对象
     *
     * @param key  唯一键，如：abc/a/a.png
     * @param file 文件
     * @return {@code PutObjectResult }
     */
    public PutObjectResult putObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key, file);
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 上传对象
     *
     * @param key  唯一键
     * @param file 文件
     * @return {@code PutObjectResult }
     */
    public PutObjectResult putPictureObject(String key,File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key, file);
        // 会对图片进行处理(拿到基本信息也被视为图片)
        PicOperations picOperations=new PicOperations();
        // 0: 不返回图片信息，1: 返回图片信息，默认为0
        picOperations.setIsPicInfo(1);
        List<PicOperations.Rule> rules=new ArrayList<>();
        // 图片压缩(转成webp格式)
        String webpKey = FileUtil.mainName(key)+".webp";
        PicOperations.Rule compressRule=new PicOperations.Rule();
        compressRule.setFileId(webpKey);
        // 压缩规则
        compressRule.setRule("imageMogr2/format/webp");
        compressRule.setBucket(cosClientConfig.getBucket());
        rules.add(compressRule);
        // 缩略图处理
        PicOperations.Rule thumbnailRule = new PicOperations.Rule();
        String thumbnailKey = FileUtil.mainName(key)+"_thumbnail."+FileUtil.getSuffix(key);
        thumbnailRule.setFileId(thumbnailKey);
        thumbnailRule.setBucket(cosClientConfig.getBucket());
        // 缩放规则(imageMogr2/thumbnail/<width>x<height>>),如果缩放后大于原图则不处理
        thumbnailRule.setRule(String.format("imageMogr2/thumbnail/%sx%s>",128,128));
        rules.add(thumbnailRule);
        // 预览图处理
        PicOperations.Rule previewRule = new PicOperations.Rule();
        String previewKey = FileUtil.mainName(key)+"_preview."+FileUtil.getSuffix(key);
        previewRule.setFileId(previewKey);
        previewRule.setBucket(cosClientConfig.getBucket());
        // 缩放规则(imageMogr2/thumbnail/800x600>),如果缩放后大于原图则不处理
        previewRule.setRule(String.format("imageMogr2/thumbnail/%sx%s>",800,600));
        rules.add(previewRule);
        // 添加规则
        picOperations.setRules(rules);
        putObjectRequest.setPicOperations(picOperations);
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 删除对象
     *
     * @param key 唯一键
     */
    public void  deleteObject(String key) {
        cosClient.deleteObject(cosClientConfig.getBucket(), key);
    }

    /**
     * 删除目录
     *
     * @param directorKey 这里是目录如：/space/123434/
     */
    public void deleteDirectory(String directorKey) {
        ListObjectsRequest  listObjectsRequest = new ListObjectsRequest();
        listObjectsRequest.setBucketName(cosClientConfig.getBucket());
        // 设置目录前缀如 /space/1234/
        listObjectsRequest.setPrefix(directorKey);
        listObjectsRequest.setDelimiter("/");

        ObjectListing objectListing;
        do {
            objectListing = cosClient.listObjects(listObjectsRequest);

            // 删除目录的所有文件
            for (COSObjectSummary cosObjectSummary : objectListing.getObjectSummaries()) {
                cosClient.deleteObject(cosClientConfig.getBucket(), cosObjectSummary.getKey());
                log.info("删除文件：{}", cosObjectSummary.getKey());
            }
            // 处理子目录
            for (String commonPrefix : objectListing.getCommonPrefixes()) {
                // 递归删除子目录
                deleteDirectory(commonPrefix);
                log.info("删除子目录：{}", commonPrefix);
            }
            // 分页处理
        } while (objectListing.isTruncated());
        cosClient.shutdown();

    }
}
